package com.zyt.springboot.CalculationPI;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class PI4 {//莱布尼茨公式求圆周率 BigDecimal
    public static void main(String[] args) {
        int precision = 100; // 精确到小数点后100位
        BigDecimal pi = calculatePi(precision);
        System.out.println(pi);
    }

    public static BigDecimal calculatePi(int precision) {
        BigDecimal pi = BigDecimal.ZERO;
        BigDecimal numerator = BigDecimal.valueOf(4);
        BigDecimal denominator = BigDecimal.ONE;
        BigDecimal term;
        int i = 0;
        do {
            term = numerator.divide(denominator, precision, RoundingMode.HALF_UP);
            if (i % 2 == 0) {
                pi = pi.add(term);
            } else {
                pi = pi.subtract(term);
            }
            denominator = denominator.add(BigDecimal.ONE.add(BigDecimal.ONE));
            i++;
        } while (term.compareTo(BigDecimal.ONE.divide(BigDecimal.TEN.pow(precision), precision, RoundingMode.HALF_UP)) >= 0);
        return pi;
    }
}
